//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
using OpenLS.Core.Notification;

namespace OpenLS.Spreadsheet.UI
{
    internal class CommandWatcher : ViewModelBase
    {
        private bool _canExecute;
        private RoutedCommand _command;
        private object _commandParameter;

        private IInputElement _source;

        public RoutedCommand Command
        {
            get { return _command; }
            set
            {
                if (_command != null)
                    _command.CanExecuteChanged -= updateCanExecute;
                _command = value;
                updateCanExecute();
                if (_command != null)
                    _command.CanExecuteChanged += updateCanExecute;
            }
        }

        public IInputElement Source
        {
            get { return _source; }
            set
            {
                _source = value;
                updateCanExecute();
            }
        }

        public object CommandParameter
        {
            get { return _commandParameter; }
            set { _commandParameter = value; }
        }

        public bool CanExecute
        {
            get { return _canExecute; }
            set
            {
                _canExecute = value;
                notifyPropertyChanged("CanExecute");
            }
        }


        private void updateCanExecute(object sender, EventArgs e)
        {
            updateCanExecute();
        }

        private void updateCanExecute()
        {
            if (Command == null)
                CanExecute = false;
            CanExecute = Command.CanExecute(CommandParameter, Application.Current.Windows[0]);
        }

    }
}